<?php
/**
 * Partner List
 * 
 * @author Xavier VILAIN
 * @package Nawa\MedicalStudy
 * @license #license#
 * 
 */

use Nawa\MedicalStudy;
use Nawa\Customer;
use Doctrine\DBAL\Connection;
use Fox\Html\Block;

$xview = Xview::instance();

$block = $xview->component('medicalstudies','partners');

$grid = $block->item('gPartners');
$ajax = $xview->val('xvtrs',false);
$msid = $xview->val('msid',false);
$mcid = $xview->val('mcid',false);
$monitoringid = $xview->val('monitoringid',false);
$reload = $xview->val('reload',false);
$uniqueData = null;
$dbPartnersId = array();

$ms =  $xview->component('medicalstudies','medicalstudy',array('allowVoid' => true));

if($reload && !empty($mcid)) {
	// Reload information for Medical Center Partners screen
	$msMedicalCenter = $ms->findMedicalCentersPartners($msid.':'.$mcid);
	$uniqueData = $msMedicalCenter->partnersData();
	foreach($uniqueData as $data) {
		$dbPartnersId[$data['customerid']] = true;
		$dbPartnersData[$data['customerid']] = $data;
	}
	if(!empty($monitoringid)) {
		$uniqueData = $dbMonitoringsPartnersId = array();
		$msMcMonitoring = $msMedicalCenter->findMonitorings($msMedicalCenter->getInlineId().':'.$monitoringid);
		foreach($msMcMonitoring->partners() as $partner) {
			if(!empty($dbPartnersId[$partner->customerid])) {
				$dbMonitoringsPartnersId[$partner->customerid] = $dbPartnersId[$partner->customerid];
				$uniqueData[$partner->customerid] = $dbPartnersData[$partner->customerid];
			} else {
				// TODO : Should not be possible
			} 
		}
		$dbPartnersId = $dbMonitoringsPartnersId;
	}
} elseif($reload && !empty($msid)) {
	// Standard case, reload information at the medicalstudy level
	foreach($ms->partners() as $partner)
	{
		/* @var $partner \Nawa\MedicalStudy\Partner */
		switch($partner->role)
		{
			case MedicalStudy::ROLE_CUSTOMER:
				break;
			default:
				$detail = $partner->getData();
				$detail['medicalcenters'] = null;
				$detail['name1'] = $partner->customer()->name1;
				foreach($partner->medicalCentersLinks() as $center)
				{
					try {
						$mc = $center->medicalCenterPartner()->medicalCenter();
					}
					catch(\Fox\Object\Exception\NotExist $e){
						continue;// Error that should not exist
					}
					$detail['medicalcenters'][] = array('label' => $mc->name1,'mcid' => $mc->mcid);
				}
				if(!empty($detail['medicalcenters'])) {
					$detail['medicalcenters'] = preg_replace("/\"/","'",json_encode($detail['medicalcenters']));
				}
				$uniqueData[$partner->customerid] = $detail;
				$dbPartnersId[$partner->customerid] = true;
				break;
		}
	}
}

if($ajax || $reload)
{
	$data = $grid->get();
	if(is_array($data['gPartners']))
	{
		foreach($data['gPartners'] as $key => $line)
		{
			if(empty($line['customerid'])) {
				continue;
			}
			$line['coche'] = false;
			if(isset($dbPartnersId[$line['customerid']])) {
				unset($dbPartnersId[$line['customerid']]);
			}
			
			if(isset($uniqueData[$line['customerid']])) {
				$uniqueData[$line['customerid']]['role'] = $line['role'];
			} else {
				$uniqueData[$line['customerid']] = $line;
			}
		}
		// Remove from display deleted partners
		foreach($dbPartnersId as $id => $value) {
			if(isset($uniqueData[$id])) {
				unset($uniqueData[$id]);
			}
		}
	}
}
if($ajax || $reload)
{
	
	$codes = Xview::instance()->val('codes');
	if(is_array($codes))
	{
		$finder = new Customer();
		$res = $finder->find(new Fox\Dao\SqlFragment('customerid IN (?)',array($codes),array(Connection::PARAM_INT_ARRAY)));
		foreach($res as $item)
		{
			$data = $item->getData();
			$data['customerid'] = $item->getId();
			$customerid = $data['customerid'];
			$data['role'] = $data['function'];

			// Auto Save Data to the MS
			//@TODO build a customizing point here
			if($ms->exists()) {
				try {
					$partner = new MedicalStudy\Partner();
					$partner->setFields($data);
					$ms->replacePartners($partner);
					$ms->prepareUpdate(MedicalStudy::CHANGE_ADD_PARTNERS);
					$ms->update();
				} catch (Fox\Object\Exception\Save $e) {
					\Fox\Message::Error($e);
				}
			}
			if(!empty($mcid)) {
				try {
					// We need to add the user into the medical center has a partner
					$mcPartner = $msMedicalCenter->findPartners("$msid:$mcid:$customerid");
					$mcPartner->setFields(array(
									'msid' => $msid,
									'mcid' => $mcid,
									'customerid' => $customerid,
									'role' => MedicalStudy\MedicalCenter\Partner::ROLE_STANDARD,
									'uname' => User::current()->getId(),
									'udate' => MedicalStudy\MedicalCenter\Partner::sqlDateTime(time())));
					if($mcPartner->exists()) {
						$mcPartner->update();
					} else {
						$mcPartner->create();
					}
					if(!empty($monitoringid) && !empty($msMcMonitoring)) {
						$mcMonitoringPartner = $msMcMonitoring->findPartners("$msid:$mcid:$monitoringid:$customerid");
						if($mcMonitoringPartner->exists()) {
							// For Now we do nothing
						} else {
							$mcMonitoringPartner->setFields(array(
									'msid' => $msid,
									'mcid' => $mcid,
									'monitoringid' => $monitoringid,
									'customerid' => $customerid,
									'role' => MedicalStudy\MedicalCenter\Partner::ROLE_STANDARD,
									'uname' => User::current()->getId(),
									'udate' => MedicalStudy\MedicalCenter\Partner::sqlDateTime(time())));
							$mcMonitoringPartner->create();
						}
					}
				} catch (Fox\Object\Exception\Save $e) {
					\Fox\Message::Error($e);
				}
			}
			$data['coche'] = false;
			$uniqueData[$item->getId()] = $data;
		}
	}
	$grid->initialize($uniqueData,true);
	echo $grid->display();
}
else
{
	return $block;
}